package com.zxg.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import com.taobao.common.dao.persistence.DBRoute;
import com.taobao.common.dao.persistence.exception.DAOException;

public class JDBCBaseDaoSupport {
  private Map<String, DataSource> dataSrcRoute      = new HashMap<String, DataSource>();

  private DataSource              defaultDataSource = null;

  public Map<String, DataSource> getDataSrcRoute() {
    return dataSrcRoute;
  }

  public void setDataSrcRoute(Map<String, DataSource> dataSrcRoute) {
    this.dataSrcRoute = dataSrcRoute;
  }

  protected DataSource getDataSrc(DBRoute dbroute) {
    DataSource ds = dataSrcRoute.get(dbroute.getXid());
    if (ds == null)
      ds = defaultDataSource;
    return ds;
  }

  public DataSource getDefaultDataSource() {
    return defaultDataSource;
  }

  public void setDefaultDataSource(DataSource defaultDataSource) {
    this.defaultDataSource = defaultDataSource;
  }

  public Connection getConnection(DBRoute dbroute) throws SQLException {
    DataSource dataSource = getDataSrc(dbroute);
    boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
    Connection springCon = null;

    springCon = (transactionAware ? dataSource.getConnection() : DataSourceUtils.doGetConnection(dataSource));

    return springCon;
  }

  public final void closeConnection(Connection conn, DBRoute dbroute) throws DAOException {
    DataSource dataSource = getDataSrc(dbroute);
    boolean transactionAware = (dataSource instanceof TransactionAwareDataSourceProxy);
    try {
      if (conn != null) {
        if (transactionAware) {
          conn.close();
        } else {
          DataSourceUtils.doReleaseConnection(conn, dataSource);
        }
      }
    } catch (Exception e) {
      throw new DAOException(e);
    }
  }

}
